package org.example.boot.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.example.boot.usercenter.common.ErrorCode;
import org.example.boot.usercenter.exception.BusinessException;
import org.example.boot.usercenter.model.entity.User;
import org.example.boot.usercenter.model.request.WeChatSessionRequest;
import org.example.boot.usercenter.model.response.WeChatSessionResponse;
import org.example.boot.usercenter.service.UserService;
import org.example.boot.usercenter.mapper.UserMapper;
import org.example.boot.usercenter.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;


/**
 * @author HEZHAOGUI
 * @description 针对表【user(用户表)】的数据库操作Service实现
 * @createDate 2025-02-23 15:29:37
 */

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    private WeChatSessionRequest weChatSessionRequest;
    @Autowired
    private ObjectMapper objectMapper;
    @Resource
    private UserMapper userMapper;

    @Override
    public String userLoginGetCode2Session(String code) {
        // 参数校验
        if (StringUtils.isBlank(code)) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        // 1.创建一个默认配置的 HTTP 客户端实例
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 2.构建URL（自动编码）
            String url = UriComponentsBuilder.fromHttpUrl(weChatSessionRequest.getJscode2sessionUrl())
                    .queryParam("appid", weChatSessionRequest.getAppid())
                    .queryParam("secret", weChatSessionRequest.getAppSecret())
                    .queryParam("js_code", code)
                    .queryParam("grant_type", "authorization_code")
                    .build()
                    .encode(StandardCharsets.UTF_8) // 统一指定编码方式
                    .toUriString();
            // 3.构建 Get请求
            HttpGet request = new HttpGet(url);
            // 4.发送HTTP请求
            try (CloseableHttpResponse response = httpClient.execute(request)) {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode != HttpStatus.SC_OK) {
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR, "微信接口异常状态码：" + statusCode);
                }
                // 5.从 HTTP 响应对象中提取实体（Entity）
                HttpEntity entity = response.getEntity();
                // 6.转化为String对象
                String jsonResponse = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                // 7.解析json 为 WeChatSessionResponse 对象
                WeChatSessionResponse weChatSessionResponse = objectMapper.readValue(jsonResponse, WeChatSessionResponse.class);
                if (StringUtils.isBlank(weChatSessionResponse.getOpenid())) {
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR, "获取openid失败");
                }
                // 获得用户的 Openid
                String openid = weChatSessionResponse.getOpenid();

                //查询数据库中是否有 Openid
                QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("openId", openid);
                User OdUser = userMapper.selectOne(queryWrapper);
                // 没有则添加到数据库中
                if (OdUser == null) {
                    User NewUser = new User();
                    NewUser.setOpenId(openid);
                    int insert = userMapper.insert(NewUser);
                    if (insert != 1) {
                        throw new BusinessException(ErrorCode.SYSTEM_ERROR);
                    }

                }
                // 生成token
                String token = JwtUtils.generateToken(weChatSessionResponse.getOpenid());
                // 8.强制释放资源
                EntityUtils.consume(entity);

                return token;
            }
        } catch (IOException e) {
            // 更规范的异常处理
            log.error("微信登录接口调用失败: {}", e.getMessage());
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "系统繁忙，请稍后再试");
        }

    }

    @Override
    public User getUserInformation(String openid) {
        if (StringUtils.isBlank(openid)){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        //查询数据库中是否有 Openid
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openId", openid);
        User OdUser = userMapper.selectOne(queryWrapper);
        if (OdUser == null) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        return getSafetyUser(OdUser);
    }

    @Override
    public User getSafetyUser(User user) {
        if (user == null) {
            return null;
        }
        User safeUser = new User();
        safeUser.setNickName(user.getNickName());
        safeUser.setAvatarUrl(user.getAvatarUrl());
        safeUser.setGender(user.getGender());
        safeUser.setPhone(user.getPhone());
        safeUser.setEmail(user.getEmail());
        safeUser.setCity(user.getCity());
        safeUser.setCountry(user.getCountry());
        safeUser.setProvince(user.getProvince());
        return safeUser;
    }

    @Override
    public String getLoginState(HttpServletRequest request) {
        if (request == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //从请求头获取token
        String token = JwtUtils.extractToken(request);
        if (token == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //解析 token 获得 openid
        String openid = JwtUtils.getTokenOpenid(token);
        if (StringUtils.isBlank(openid)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return openid;
    }

    @Override
    public int updateUser(User user ,String loginState) {
        if (user == null){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        if (StringUtils.isBlank(loginState)){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        //查询数据库中是否有存储用户的信息
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openId", loginState);
        User OdUser = userMapper.selectOne(queryWrapper);
        if (OdUser == null){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"找不到有关的数据");
        }
        user.setAvatarUrl(OdUser.getAvatarUrl());
        return userMapper.updateById(user);
    }
}






